package com.ruoyi.lightkillPest.controller.device;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.lightkillPest.domain.device.SCDDeviceBatteryInfo;
import com.ruoyi.lightkillPest.domain.device.SCDDeviceDao;
import com.ruoyi.lightkillPest.mapper.SCDDeviceMapper;
import com.ruoyi.lightkillPest.service.SCDDeviceService;
import com.ruoyi.permission.Dao.SerDevicePermi;
import com.ruoyi.permission.domain.BaseBlockPermiDeviceInfo;
import com.ruoyi.permission.domain.BlockPermiDeviceInfo;
import com.ruoyi.permission.mapper.SerDevicePermiMapper;
import com.ruoyi.permission.mapper.SerUnitUserMapper;
import com.ruoyi.permission.service.PermiService;
import com.ruoyi.utils.LocationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/SCD/device")
public class SCDDeviceController {

    @Autowired
    SCDDeviceService scdDeviceService;

    @Autowired
    SCDDeviceMapper scdDeviceMapper;

    @Autowired
    SerDevicePermiMapper devicePermiMapper;

    @Autowired
    SerUnitUserMapper unitUserMapper;

    @Autowired
    private PermiService permiService;

    /**
     * 按条件获取杀虫灯设备
     * @param deviceInfo
     * @return TableDataInfo
     */
    @GetMapping("/selectSCDDeviceInfoByCondition")
    public TableDataInfo selectDeviceInfoByCondition(SCDDeviceDao deviceInfo) {
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        Integer userId=Integer.valueOf(userIdL.intValue());
        Integer unitId = 0;
        if(userId != 1 && userIdL != 20) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        //管理员
        if(unitId == 0) {
            List<SerDevicePermi> serDevicePermiList = new ArrayList<>();
            return scdDeviceService.selectDeviceInfoByCondition(deviceInfo,serDevicePermiList);
        }else{
            //获取单位下所有设备
            List<BaseBlockPermiDeviceInfo> baseBlockPermiDeviceInfoList = permiService.selectAllDeviceByUnitId(unitId);
            List<SerDevicePermi> SCDDevicePermiList = new ArrayList<>();
            for(BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo:baseBlockPermiDeviceInfoList) {
                if (baseBlockPermiDeviceInfo.getTypeId() == 5) {
                    SerDevicePermi serDevicePermi = new SerDevicePermi().setDeviceName(baseBlockPermiDeviceInfo.getDeviceName()).setDeviceNo(baseBlockPermiDeviceInfo.getDeviceId())
                            .setDeviceType(baseBlockPermiDeviceInfo.getDeviceType()).setDeviceSerial(baseBlockPermiDeviceInfo.getDeviceSerial()).setId(baseBlockPermiDeviceInfo.getId());
                    SCDDevicePermiList.add(serDevicePermi);
                }
            }
            return scdDeviceService.selectDeviceInfoByCondition(deviceInfo,SCDDevicePermiList);
        }

    }

    /**
     * 获取所有杀虫灯设备
     * @return
     */
    @GetMapping("/selectAllSCDDeviceInfo")
    public TableDataInfo selectAllSCDDeviceInfo(){
        Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
        Integer userId=Integer.valueOf(userIdL.intValue());
        Integer unitId = 0;
        if(userId != 1 && userId != 20) {
            unitId = unitUserMapper.selectByPrimaryKey(userId).getUnitId();
        }
        //管理员则返回所有设备
        if(unitId == 0) {
            return scdDeviceService.selectAllDeviceInfo();
        }else {
            //获取单位下所有设备
            List<BaseBlockPermiDeviceInfo> baseBlockPermiDeviceInfoList = permiService.selectAllDeviceByUnitId(unitId);
            List<SerDevicePermi> SCDDevicePermiList = new ArrayList<>();
            for(BaseBlockPermiDeviceInfo baseBlockPermiDeviceInfo:baseBlockPermiDeviceInfoList) {
                if (baseBlockPermiDeviceInfo.getTypeId() == 5) {
                    SerDevicePermi serDevicePermi = new SerDevicePermi().setDeviceName(baseBlockPermiDeviceInfo.getDeviceName()).setDeviceNo(baseBlockPermiDeviceInfo.getDeviceId())
                            .setDeviceType(baseBlockPermiDeviceInfo.getDeviceType()).setDeviceSerial(baseBlockPermiDeviceInfo.getDeviceSerial()).setId(baseBlockPermiDeviceInfo.getId());
                    SCDDevicePermiList.add(serDevicePermi);
                }
            }
            SCDDeviceDao deviceInfo = new SCDDeviceDao();
            return scdDeviceService.selectDeviceInfoByCondition(deviceInfo,SCDDevicePermiList);
        }
    }

    /**
     * 更新设备昵称
     * @param deviceId
     * @param nickName
     * @return
     */
    @PostMapping("/updateNickName")
    public AjaxResult updateSCDDeviceNickName(String deviceId,String nickName){
        SCDDeviceDao deviceInfo = scdDeviceMapper.selectSCDDeviceInfo(deviceId);
        SerDevicePermi serDevicePermi = devicePermiMapper.selectByDeviceSerial(deviceId);
        deviceInfo.setNickName(nickName);
        serDevicePermi.setDeviceName(nickName);
        int i = scdDeviceMapper.updateNickName(deviceInfo) + devicePermiMapper.updateByPrimaryKeySelective(serDevicePermi);
        if(i>0){
            return AjaxResult.success("更新成功");
        }else{
            return AjaxResult.error("更新失败");
        }
    }

    /**
     * 更新设备地区信息
     * @param scdDeviceDao
     * @return
     * @throws IOException
     */
    @PostMapping("/updateSCDDeviceInfo")
    public AjaxResult updateSCDDeviceInfo(SCDDeviceDao scdDeviceDao) throws IOException {
        if(scdDeviceDao.getLocation()!=null && scdDeviceDao.getLocation()!=""){
            double[] location = LocationUtil.geocode(scdDeviceDao.getLocation());
            Double longitudeFinal = location[0];
            Double latitudeFinal = location[1];
            scdDeviceDao.setLongitudeFinal(longitudeFinal);
            scdDeviceDao.setLatitudeFinal(latitudeFinal);
            JSONObject locationObject = LocationUtil.reverseGeoCode(longitudeFinal,latitudeFinal);
            //详细地址，用于更新各个表中的地址
//            String locationStr = locationObject.getString("formattedAddress");
            String area = locationObject.getString("city") + locationObject.getString("district");
            String province = locationObject.getString("province");
            if(devicePermiMapper.selectByDeviceSerial(scdDeviceDao.getDeviceId()) != null){
                SerDevicePermi devicePermiInfo = devicePermiMapper.selectByDeviceSerial(scdDeviceDao.getDeviceId());
                devicePermiInfo.setArea(area);
                devicePermiInfo.setProvince(province);
                devicePermiInfo.setLongitude(longitudeFinal);
                devicePermiInfo.setLatitude(latitudeFinal);
                devicePermiMapper.updateByPrimaryKeySelective(devicePermiInfo);
//                if(j > 0){
//                    return AjaxResult.success("更新权限设备的地区信息成功");
//                }else {
//                    return AjaxResult.error("更新权限设备的地区信息失败");
//                }
            }

        }
        int i = scdDeviceMapper.updateSCDDeviceInfo(scdDeviceDao);
        if(i>0){
            return AjaxResult.success("更新成功");
        }else{
            return AjaxResult.error("更新失败");
        }
    }
    /**
     * 后端测试使用
     * @return
     */
    @GetMapping("/updateDeviceStatus")
    public AjaxResult updateDeviceStatus(){
        scdDeviceService.updateDeviceStatus();
        return AjaxResult.success("更新成功");
    }

    /**
     * 根据设备号获取电量信息列表
     * @param deviceId
     * @return
     */
    @GetMapping("/getBatteryInfo")
    public AjaxResult getBatteryInfoBydeviceId(String deviceId){
        List<SCDDeviceBatteryInfo> scdDeviceBatteryInfos = scdDeviceMapper.selectBatteryInfoListByDeviceId(deviceId);
        return AjaxResult.success(scdDeviceBatteryInfos);
    }

}
